<?php


class Security extends App {
	
	public static function Init () {
		if (!DB::CheckTable("security")) {
			DB::Query("CREATE TABLE `security` (
			`id` INT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
			`var` VARCHAR( 50 ) NOT NULL ,
			`val` VARCHAR( 255 ) NOT NULL ,
			`when` DATETIME NOT NULL
			) ENGINE = MEMORY;");
		}
		if (!DB::CheckTable("securitybl")) {
			DB::Query("CREATE TABLE `securitybl` (
			`id` INT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
			`var` VARCHAR( 50 ) NOT NULL ,
			`ip` VARCHAR( 15 ) NOT NULL ,
			`val` VARCHAR( 255 ) NOT NULL ,
			`when` DATETIME NOT NULL
			) ENGINE = InnoDB;");
		}
		
		$deletetimeout = 3600*24;	// blockage lasts 1 day
		self::DeleteBlockage($deletetimeout);
	}
	
	public static function DeleteBlockage($deletetimeout=86400) {
		DB::Query("DELETE FROM `securitybl` WHERE `when` < '".date("Y-m-d H:i:s", time()-$deletetimeout)."' AND `val` != 'forever';");
	}
	
	public static function ClearMem ($timeout=3600) {
		DB::Query("DELETE FROM `security` WHERE `when` < '".date("Y-m-d H:i:s", time()-$timeout)."';");
	}
	
	public static function AntiPostFlood($maxpost=3, $intime=1800) {
		if ($_SERVER['REQUEST_METHOD']=='POST') {
			self::ClearMem();
			$userid = md5($_SERVER['REMOTE_ADDR'].":".$_SERVER['REQUEST_URI']);
			// check for blockage
			$blocked = DB::GetOneByQuery("SELECT COUNT(*) FROM `securitybl` WHERE `var`='{$userid}' AND `ip`='{$_SERVER['REMOTE_ADDR']}' AND `val` like 'block-posts%';");
			if ($blocked&&$blocked>0) return false; // USER IS ALREADY BLOCKED
			
			// check for earlier posts 
			$lastposts = DB::DumpQuery("SELECT `id`,`val`,UNIX_TIMESTAMP(`when`) as 'when' FROM `security` WHERE `var`='{$userid}' AND `when` BETWEEN '".date("Y-m-d H:i:s", time()-$intime)."' AND '".date("Y-m-d H:i:s")."' ORDER BY `when` DESC");
			$postcount = count($lastposts);
			if ($postcount<$maxpost) {		// ALLOW POST
				$d = array(
					"var"=>$userid,
					"val"=>"post",
					"when"=>date("Y-m-d H:i:s")
					);
				DB::Insert("security", $d);
				return true;
			}else{		// EXCEEDED LIMITS !!!
				$d = array(
					"var"=>$userid,
					"ip"=>$_SERVER['REMOTE_ADDR'],
					"val"=>"block-posts-timed",
					"when"=>date("Y-m-d H:i:s")
					);
				DB::Insert("securitybl", $d);
				return false;
			}
		}
	}
	
	public static function UnInit () {
		// Get all queries, look for update and inserts
		// If ip is detected as flooding, then mark all of that ip's insert and updates
	}
}

?>
